package com.LeeCode;

import java.util.HashMap;


/**
 * 元音辅音字符串计数 II
 */

public class Code3306 {
    public static void main(String[] args) {
        String word = "ieaouqqieaouqq";
        int k = 1;
        System.out.println(new Code3306().countOfSubstrings(word, k));
    }

    public long countOfSubstrings(String word, int k) {
        char[] chars = word.toCharArray();

        return aux(chars, k) - aux(chars, k + 1);
    }

    private long aux(char[] word, int k) {
        long ans = 0;
        // 这里用哈希表实现，替换成数组会更快
        HashMap<Character, Integer> cnt1 = new HashMap<>(); // 每种元音的个数
        int cnt2 = 0; // 辅音个数
        int left = 0;
        for (char b : word) {
            if ("aeiou".indexOf(b) >= 0) {
                cnt1.merge(b, 1, Integer::sum); // ++cnt1[b]
            } else {
                cnt2++;
            }
            while (cnt1.size() == 5 && cnt2 >= k) {
                char out = word[left];
                if ("aeiou".indexOf(out) >= 0) {
                    // 值为 0 时删除键
                    cnt1.merge(out, -1, (old, delta) -> {
                        int res = old + delta;
                        return res == 0 ? null : res;
                    });
                } else {
                    cnt2--;
                }
                left++;
            }
            ans += left;
        }
        return ans;
    }
}
